<template>
  <div class="univer-view">
    <div class="univer-view-toolbar" style="display: flex;">
      <input type="file" id="fileInput" accept=".xlsx, .xls" :disabled="loading" />
      <button @click="importData" :disabled="loading">导入 表格</button>
      <div style="width: 100px;"></div>
      <button @click="exportAllData" :disabled="loading">导出 全部 数据</button>
    </div>
    <div ref="container" class="container" />
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'

import { setupUniver } from './setupUniver'
import { workbookToExcel } from './toExcel'
import { excelToWorkbook } from './toWorkBook'

const container = ref(null)
const univerApi = ref(null)
const loading = ref(false)

onMounted(() => {
  const univer = setupUniver({
    container: container.value
  })

  window.univerApi = univer
  univerApi.value = univer
})

const importData = async () => {
  const fileInput = document.getElementById('fileInput')
  const file = fileInput.files[0]
  if (file) {
    loading.value = true
    try {
      const workbookData = await excelToWorkbook(file)
      console.log('workbookData', workbookData)

      // 清空 现有工作表
      const fWorkbook = univerApi.value.getActiveWorkbook()
      const unitId = fWorkbook?.getId()

      if (unitId) {
        univerApi.value.disposeUnit(unitId)
      }

      // 创建新工作表
      // univerApi.value.createWorkbook(tableData)
      univerApi.value.createWorkbook(workbookData)

    } catch (error) {
      console.error('导入失败:', error)
    }
    loading.value = false
  }
}

const exportAllData = async () => {
  const activeWorkbook = univerApi.value.getActiveWorkbook()
  if (!activeWorkbook)
    throw new Error('activeWorkbook is not defined')

  const snapshot = activeWorkbook.save()

  console.log(snapshot)
  await workbookToExcel(snapshot)
}

onBeforeUnmount(() => {
  univerApi.value = null
})
</script>

<style lang="less" scoped>
.univer-view {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  &-toolbar {
    padding: 8px 16px;
    border-bottom: 1px solid rgb(229, 229, 229);
    flex-shrink: 1;

    button {
      background: #fff;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      padding: 4px 8px;
      cursor: pointer;

      &+button {
        margin-left: 8px;
      }
    }
  }

  .container {
    width: 100%;
    height: 100%;
    flex: 1;
  }
}
</style>
